package notice_logic

import (
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/interface/service"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

// SendEmailTimeTo 发送定时邮件
func (cls *Notice) SendEmailTimeTo(ctx context.Context, to []string, cc []string, bcc []string, subject string, bodyType model.SystemSmtpLogBodyType, body string, attachments []*model.SystemObject, timeTo int64) errors.Error {
	var fields []service.SystemSmtpLogField
	if 0 != len(cc) {
		fields = append(fields, service.SystemSmtpLogFieldWithCc(cc...))
	}

	if 0 != len(bcc) {
		fields = append(fields, service.SystemSmtpLogFieldWithBcc(bcc...))
	}

	return cls.smtp.WithTransaction(ctx, func(ctx context.Context) errors.Error {
		if err := cls.smtp.LogTimeTo(ctx, to, subject, bodyType, body, attachments, timeTo, fields...); nil != err {
			return err.Relation(errors.ErrorServerInternalError("IGLNL_IC.N_CE.SETT_TO.233906", "保存邮件发送日志失败"))
		}

		for _, object := range attachments {
			if err := cls.storage.PersistenceObject(ctx, object); nil != err {
				return err.Relation(errors.ErrorServerInternalError("IGLNL_IC.N_CE.SETT_TO.384030", "持久化附件失败"))
			}
		}

		return nil
	})
}
